package org.iabako.server.dao.report;

import org.iabako.shared.dto.FinancesBalance;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jose on 28/01/15.
 */

@Repository("expenseReportDAO")
public class ExpenseReportDAO extends AbstractReportDAO {

    public Map<Object, FinancesBalance> getExpenses(Date dateAfter, Date dateBefore) {

        Map<Object, FinancesBalance> expensesByCategory = new HashMap<Object, FinancesBalance>();

        String query = "SELECT e.category, SUM(e.paymentValue) FROM Expense e " +
                "WHERE e.paymentDate >= :dateAfter AND e.paymentDate < :dateBefore " +
                "AND e.paymentMethod IS NULL " +
                "AND e.enterprise IN (:enterprises) " +
                "GROUP BY e.category";

        List<Object[]> result = (List<Object[]>) entityManager.createQuery(query).
                setParameter("dateAfter", dateAfter).setParameter("dateBefore", dateBefore).
                setParameter("enterprises", getSessionUser().getEnterprise().getVisibleEnterprisesFinancialData()).getResultList();

        addExpenseToMapByEntity(expensesByCategory, result, false);

        query = "SELECT e.category, SUM(e.paymentValue) FROM Expense e " +
                "WHERE e.paymentDate >= :dateAfter AND e.paymentDate < :dateBefore " +
                "AND e.paymentMethod IS NOT NULL " +
                "AND e.enterprise IN (:enterprises) " +
                "GROUP BY e.category";

        result = (List<Object[]>) entityManager.createQuery(query).
                setParameter("dateAfter", dateAfter).setParameter("dateBefore", dateBefore).
                setParameter("enterprises", getSessionUser().getEnterprise().getVisibleEnterprisesFinancialData()).getResultList();

        addExpenseToMapByEntity(expensesByCategory, result, true);

        return expensesByCategory;
    }
}
